Server ActionsでInfinite Scroll
別に何も難しくない
Server Actionsだからどうのという要素がない
https://gyazo.com/74881c1b7988a77ed6f67bf12339316b
code:ts
type LoadMore<T> = {
getNext: () => Promise<T[]>;
handleLoad: (items: T[]) => void;
};
const useLoadMore = <T,>({ getNext, handleLoad }: LoadMore<T>) => {
const ref = useRef<HTMLDivElement | null>(null);
const loadMore = useCallback(async () => {
if (isLoading || !hasMore) return;
setIsLoading(true);
try {
const newItems = await getNext();
if (newItems.length === 0) {
setHasMore(false);
} else {
handleLoad(newItems);
}
} catch (error) {
console.error(error);
} finally {
setIsLoading(false);
}
useEffect(() => {
const observer = new IntersectionObserver(entries => {
if (entries0.isIntersecting) { loadMore();
}
});
if (ref.current) {
observer.observe(ref.current);
}
return () => observer.disconnect();
const Sentinel = () => <div ref={ref} style={{ height: '20px' }} />;
return { Sentinel, isLoading };
};
要素の高さを計算してどうのこうのということをしないで済む